package com.itaem.community.modules.infrastructure.authority.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itaem.community.core.annotations.ResponseResult;
import com.itaem.community.core.entity.Entity;
import com.itaem.community.core.entity.PageData;
import com.itaem.community.core.exception.common.IllegalParameterException;
import com.itaem.community.core.exception.data.NoSuchDataException;
import com.itaem.community.core.utils.PageUtils;
import com.itaem.community.modules.infrastructure.authority.dto.permission.PermissionCreateDTO;
import com.itaem.community.modules.infrastructure.authority.dto.permission.PermissionUpdateDTO;
import com.itaem.community.modules.infrastructure.authority.dto.role.RoleCreateDTO;
import com.itaem.community.modules.infrastructure.authority.dto.role.RoleDTO;
import com.itaem.community.modules.infrastructure.authority.dto.role.RolePermissionLinkDTO;
import com.itaem.community.modules.infrastructure.authority.dto.role.RoleUpdateDTO;
import com.itaem.community.modules.infrastructure.authority.entity.permission.PermissionEntity;
import com.itaem.community.modules.infrastructure.authority.entity.role.RolePermissionEntity;
import com.itaem.community.modules.infrastructure.authority.mapper.permission.PermissionTransformer;
import com.itaem.community.modules.infrastructure.authority.mapper.role.RoleTransformer;
import com.itaem.community.modules.infrastructure.authority.service.permission.PermissionService;
import com.itaem.community.modules.infrastructure.authority.service.role.RolePermissionService;
import com.itaem.community.modules.infrastructure.authority.service.role.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;


/**
 * <p>
 * 用户角色表 前端控制器
 * </p>
 *
 * @author tomato
 * @since 2020-10-28
 */
@Slf4j
@Api(tags = "权限管理模块")
@ResponseResult
@RestController
@RequestMapping("/authority")
public class AuthorityController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleTransformer roleTransformer;

    @Autowired
    private PermissionTransformer permissionTransformer;

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("分页查询角色信息")
    @GetMapping("/role/{page}/{size}")
    public PageData listRole(
            @ApiParam(value = "页码", example = "1") @PathVariable Integer page,
            @ApiParam(value = "大小", example = "15") @PathVariable Integer size
    ) {
        return PageUtils.extract(roleService.page(new Page<>(page, size)))
                // 转换实体类
                .map(roleTransformer::entityToBriefDto);
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("获取单个角色的信息")
    @GetMapping("/role/{id}")
    public RoleDTO getRole(@ApiParam("角色id") @PathVariable("id") Integer roleId) {
        return roleService.findRoleById(roleId);
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("新增角色")
    @PostMapping("/role")
    public Boolean saveRole(@Valid @RequestBody RoleCreateDTO createDto) {
        return roleService.save(roleTransformer.createDtoToEntity(createDto));
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("更新角色信息")
    @PatchMapping("/role")
    public Boolean updateRole(@Valid @RequestBody RoleUpdateDTO updateDto) {
        return roleService.updateById(roleTransformer.updateDtoToEntity(updateDto));
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("删除角色")
    @DeleteMapping("/role/{id}")
    public Boolean removeRole(@ApiParam("角色id") @PathVariable Long id) {
        Optional.ofNullable(roleService.getById(id))
                .orElseThrow(() -> new NoSuchDataException("不存在此角色"));
        roleService.removeById(id);
        return Boolean.TRUE;
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("为角色添加权限")
    @PostMapping("/role/{id}/permission")
    public Boolean addPermission(
            @ApiParam("角色id") @PathVariable("id") Integer roleId,
            @Valid @RequestBody RolePermissionLinkDTO linkDto) {
        if (roleId == null) {
            throw new IllegalParameterException("角色id不能为空");
        }
        return roleService.addPermission(roleId, linkDto);
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("解绑角色拥有的某个权限")
    @DeleteMapping("/role/{roleId}/permission/{permissionId}")
    public Boolean removePermission(
            @ApiParam("角色id") @PathVariable Integer roleId,
            @ApiParam("权限id") @PathVariable Integer permissionId
    ) {
        rolePermissionService.remove(
                new QueryWrapper<RolePermissionEntity>()
                        .lambda()
                        .eq(RolePermissionEntity::getRoleId, roleId)
                        .eq(RolePermissionEntity::getPermissionId, permissionId)
        );
        return Boolean.TRUE;
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("分页查询权限")
    @GetMapping("/{page}/{size}")
    public PageData listPermission(
            @ApiParam(value = "页码", example = "1") @PathVariable Integer page,
            @ApiParam(value = "大小", example = "15") @PathVariable Integer size
    ) {
        return PageUtils.extract(permissionService.page(new Page<>(page, size)))
                .map(permissionTransformer::entityToBriefDto);
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("获取单个权限的信息")
    @GetMapping("/permission/{id}")
    public Object getPermission(@ApiParam("权限id") @PathVariable("id") Integer permissionId) {
        return permissionService.findPermissionById(permissionId);
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("新增权限")
    @PostMapping("/permission")
    public Boolean savePermission(@Valid @RequestBody PermissionCreateDTO createDto) {
        return permissionService.save(permissionTransformer.createDtoToEntity(createDto));
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("更新权限信息")
    @PatchMapping("/permission")
    public Boolean updatePermission(@Valid @RequestBody PermissionUpdateDTO updateDto) {
        // 对数据库记录判空
        if (permissionService.count(
                new QueryWrapper<PermissionEntity>()
                        .lambda()
                        .eq(Entity::getId, updateDto.getId())
        ) < 1) {
            throw new NoSuchDataException("不存在指定的权限");
        }

        log.warn(permissionTransformer.updateDtoToEntity(updateDto).toString());

        // 执行更新
        return permissionService.updateById(permissionTransformer.updateDtoToEntity(updateDto));
    }

//    @RequiresRoles(value = {"超级管理员"}, logical = Logical.OR)
    @ApiOperation("删除权限")
    @DeleteMapping("/permission/{id}")
    public Boolean removePermission(@ApiParam("权限id") @PathVariable("id") Integer permissionId) {
        return permissionService.removePermissionById(permissionId);
    }
}

